package com.youdoneed.community.group.service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumnoticeMapper;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.service.ForumServciceStatic;
import com.youdoneed.community.group.dao.ForumgroupMapper;
import com.youdoneed.community.group.dao.ForumgroupinvitationrecordMapper;
import com.youdoneed.community.group.dao.ForumuserapplyjoingrouprecordMapper;
import com.youdoneed.community.group.dao.ForumuserinforumgroupMapper;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.group.entity.Forumgroupinvitationrecord;
import com.youdoneed.community.group.entity.Forumuserapplyjoingrouprecord;
import com.youdoneed.community.group.entity.Forumuserinforumgroup;
import com.youdoneed.community.group.vo.BatchVo;
import com.youdoneed.community.group.vo.ForumInUserGroupVo;
import com.youdoneed.community.group.vo.ForumgroupInUserVo;
import com.youdoneed.community.group.vo.HuanxinJson;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.FocusRegion;
import com.youdoneed.user.model.User;

@Service
public class ForumgroupService {
	private final Logger logger = LoggerFactory.getLogger(ForumgroupService.class);
	//群默认最大人数
	private static int maxusers = 2000;
	//群隐私(true :公开 ,false :非公开)
	private boolean privacy;
	//进群是否需要群主或者管理员通过(true :需要 ,false :不需要)
	private boolean members_only;
	
	private String privacys = "公开";
	
	 private static final Gson GSON = new Gson();
	@Autowired
	ForumgroupMapper forumgroupMapper;
	
	@Autowired
	ForumuserinforumgroupMapper forumuserinforumgroupMapper;
	
	@Autowired
	ForumuserapplyjoingrouprecordMapper forumuserapplyjoingrouprecordMapper;
	
	@Autowired
	ForumgroupinvitationrecordMapper forumgroupinvitationrecordMapper;
	
	@Autowired
    UserFeignClient userFeignClient;
	
	@Autowired
    FriendsClient friendsClient;
	
	@Autowired
	ForumnoticeMapper forumnoticeMapper;
	/**
	 * 创建小组
	 * @param forumgroup
	 * @param userId
	 * @author lixs
	 * @Date 2017.7.28
	 */
	@Transactional
	public String saveForumGroup(Forumgroup forumgroup,List<String> userId){
		logger.info("saveForumGroup!");
		if(null == forumgroup){	
			throw new AppException("forumgroup参数为空！");
		}
		if(userId==null){
			throw new AppException("userId参数为空");
		}
		if(userId.size()<2){
			throw new AppException("邀请人数必须超过两人才能建组哦");
		}
		if(!StringUtils.hasText(forumgroup.getGroupName())){
			throw new AppException("小组名称不能为空");
		}
		if(forumgroup.getGroupName().length()>15){
			throw new AppException("小组名称长度不能超过15个字符");
		}
		if(forumgroup.getPrivacySetting()==null){
			throw new AppException("群组隐私不能为空");
		}
		//经纬度不需要强制输入
//		if(forumgroup.getLongitude()==null){
//			throw new AppException("创建小组的经度不能为空");
//		}
//		if(forumgroup.getLatitude()==null){
//			throw new AppException("创建小组的纬度不能为空");
//		}
		if(!StringUtils.hasText(forumgroup.getLeaderUserId())){
			throw new AppException("群主的id不能为空");
		}
//		if(!StringUtils.hasText(forumgroup.getAddress())){
//			throw new AppException("群组的地址不能为空");
//		}
		//判断邀请的用户中是否包含群主id
		for(String userid:userId){
			if(userid.equals(forumgroup.getLeaderUserId())){
				throw new AppException("邀请的好友不能包含群主自己");
			}
		}	
		
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_public){
			privacy=true;
			members_only=false;
		}else{
			privacy=false;
			members_only=true;
		}
		logger.info("privacy"+privacy);
		logger.info("members_only"+members_only);
		//调用环信接口，创建小组
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("groupname", forumgroup.getGroupName());
		resultMap.put("desc", "这是一个分享快乐的小组!");
		resultMap.put("public",privacy);
		//设置群最大人数（包含群主）
		resultMap.put("maxusers", maxusers);
		resultMap.put("members_only", members_only);
		//allowinvites 是否允许群成员邀请别人加入此群。 true：允许群成员邀请人加入此群
		resultMap.put("allowinvites", true);
		resultMap.put("owner",forumgroup.getLeaderUserId());
		resultMap.put("members", userId.toArray(new String[userId.size()]));

		//解析环信返回的json
		String result = friendsClient.createGroupUser(resultMap).getData();
		HuanxinJson huanxinJson = GSON.fromJson(result, HuanxinJson.class);
		//创建小组
		Forumgroup forumgroupNew = new Forumgroup();
		forumgroupNew.setCreateDate(new Date());
		forumgroupNew.setMemberCount(userId.size()+1);
		forumgroupNew.setHeadUrl(forumgroup.getHeadUrl());
		forumgroupNew.setForumGroupId(StringUUIdUtil.getUUID()); 
		forumgroupNew.setPrivacySetting(forumgroup.getPrivacySetting());
		forumgroupNew.setGroupName(forumgroup.getGroupName());
		forumgroupNew.setLeaderUserId(forumgroup.getLeaderUserId());
		//小组创建者的昵称和头像是动态从用户表中获取。
		forumgroupNew.setLeaderUserNickname(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getName());
		forumgroupNew.setLeaderUserHeadUrl(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getImageUrl());
		forumgroupNew.setLongitude(forumgroup.getLongitude());
		forumgroupNew.setLatitude(forumgroup.getLatitude());
		forumgroupNew.setGroupIntroduction("这是一个分享快乐的小组!");
		forumgroupNew.setGroupMessageTotal(0);
		forumgroupNew.setHuanxinGroupId(huanxinJson.data.groupid);
		//默认是用户小组
		forumgroupNew.setGroupType(ForumgroupStatic.forum_group_type_for_user);
		forumgroupNew.setAddress(forumgroup.getAddress());
		//默认群组类型是“其他”
		forumgroupNew.setGroupStyle(ForumgroupStatic.forum_group_for_other);
		//没有选定默认的图片
		forumgroupNew.setGroupBackgroundUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/15x0ph5iiwd6wa8s2ta3.png");
		forumgroupNew.setGroupNotice("创建了"+forumgroup.getGroupName()+"小组");
		forumgroupNew.setCountPeopleToBeAudited(0);
		forumgroupMapper.insertSelective(forumgroupNew);
		
		//默认将群主邀请的用户存入邀请的记录中
		for(int i=0;i<userId.size();i++){
		Forumgroupinvitationrecord forumgroupinvitationrecord = new Forumgroupinvitationrecord();
		forumgroupinvitationrecord.setInviteStatus(ForumgroupStatic.invite_status_agree);
		forumgroupinvitationrecord.setCreateDate(new Date());
		forumgroupinvitationrecord.setGroupId(forumgroupNew.getForumGroupId());
		forumgroupinvitationrecord.setGroupInvitationRecordId(StringUUIdUtil.getUUID());
		forumgroupinvitationrecord.setInvitedUserId(userId.get(i));
		forumgroupinvitationrecord.setUserHeadUrl(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getImageUrl());
		forumgroupinvitationrecord.setUserId(forumgroupNew.getLeaderUserId());
		forumgroupinvitationrecord.setUserNickName(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getName());
		forumgroupinvitationrecordMapper.insertSelective(forumgroupinvitationrecord);
		}
		
		
		//保存邀请通知
		for(int i=0;i<userId.size();i++){
			logger.info("循环的次数"+i);
		Forumnotice forumnotice = new Forumnotice();
		forumnotice.setCreateDate(new Date());
		forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
		forumnotice.setNoticeType(ForumServciceStatic.gpInvitationNotice);
		forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getImageUrl());
		forumnotice.setNoticeUserId(forumgroupNew.getLeaderUserId());
		forumnotice.setReadStatus(Forumnotice.UN_READ);
		forumnotice.setSourceId(forumgroupNew.getForumGroupId());
		forumnotice.setUserId(userId.get(i));
		forumnotice.setNoticeUserNickname(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getName());
		forumnotice.setSourceDesc(forumgroup.getGroupName());
		forumnoticeMapper.insertSelective(forumnotice);
		}
				
		//创建小组与组员的关联
		for(int i=0;i<userId.size();i++){
		Forumuserinforumgroup forumuserinforumgroup = new Forumuserinforumgroup();
		forumuserinforumgroup.setUserInForumGroupId(StringUUIdUtil.getUUID());
		forumuserinforumgroup.setCreateDate(new Date());
		forumuserinforumgroup.setForumGroupId(forumgroupNew.getForumGroupId());
		forumuserinforumgroup.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
		forumuserinforumgroup.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
		forumuserinforumgroup.setUserId(userId.get(i));
		forumuserinforumgroupMapper.insert(forumuserinforumgroup);
		}
		
		//创建群主与小组的关联
		Forumuserinforumgroup forumuserinforumgroupLeader = new Forumuserinforumgroup();
		forumuserinforumgroupLeader.setUserInForumGroupId(StringUUIdUtil.getUUID());
		forumuserinforumgroupLeader.setCreateDate(new Date());
		forumuserinforumgroupLeader.setForumGroupId(forumgroupNew.getForumGroupId());
		forumuserinforumgroupLeader.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
		forumuserinforumgroupLeader.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
		forumuserinforumgroupLeader.setUserId(forumgroup.getLeaderUserId());
		forumuserinforumgroupMapper.insert(forumuserinforumgroupLeader);
		return forumgroupNew.getForumGroupId();
		
		
	}
	
	/**
	 * 查找我的小组
	 * @param userId
	 * @return List<Forumgroup>
	 * @author lid
	 * @date 2017.6.25
	 */
	@Transactional
	public List<Forumgroup> getMyGroups(String userId,Integer rows,Integer currentPage){
		/**
		 * lxs
		 */
		if(!StringUtils.hasText(userId)){
			throw new AppException("userId参数为空");
		}
		PageHelper.startPage(currentPage,rows);
		List<Forumgroup> forumgroup = forumgroupMapper.getMyGroups(userId,ForumgroupStatic.forum_group_type_for_delete);
		if(forumgroup==null){
			throw new AppException("您还未加入小组或您加入的小组已解散");
		}	
		return forumgroup;
	}
	
	/**
	 * 查找我加入的群组
	 * @param userId
	 * @return List<Forumgroup>
	 */
	@Transactional
	public List<Forumgroup> getMyGroups(String userId){
		if(!StringUtils.hasText(userId)){
			throw new AppException("userId参数为空");
		}
		return forumgroupMapper.getMyGroups(userId,ForumgroupStatic.forum_group_type_for_delete);
	}
	
	/**
	 * 查找附近的小组
	 * @param longitude
	 * @param latitude
	 * @return List<ForumInUserGroupVo>
	 * @author lixs
	 * @date 2017.7.14
	 */
	@Transactional
	public List<ForumInUserGroupVo> getNearByGroups(Double userLongitud,  Double uerLatitude,Integer distance,String userId,Integer currentPage,Integer rows){
		if(userLongitud==null){
			throw new AppException("用户经度不能为空");
		}
		if(uerLatitude==null){
			throw new AppException("用户纬度不能为空");
		}
		if(distance==null){
			throw new AppException("用户设置的距离不能为空");
		}
		
		PageHelper.startPage(currentPage, rows);
		
		ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();
		if(null==focusRegion){
		logger.info("关注区域为空");
		double ratio = Math.cos(uerLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  userLongitud - longitudeDistance;
        Double maxLongitude =  userLongitud + longitudeDistance;
        Double minLatitude = uerLatitude - latitudeDistance;
        Double maxLatitude = uerLatitude + latitudeDistance;
        return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,userLongitud,uerLatitude,distance,ForumgroupStatic.privacy_public);
		}
		logger.info("关注区域不为空");
		Double latitude = focusRegion.getData().getLatitude();
		Double longitud = focusRegion.getData().getLongitude();
			
		double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  longitud - longitudeDistance;
        Double maxLongitude =  longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;
        return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,userLongitud,uerLatitude,distance,ForumgroupStatic.privacy_public);	
	}
	
	/**
	 * 加入小组
	 * @param userId
	 * @param groupId
	 * @return boolean
	 * @author lid
	 * @date 2017.6.25
	 */
	@Transactional
	public boolean joinGroup(String userId, String groupId){
		/**
		 * lxs
		 */
		logger.info("加入小组");
		if(!StringUtils.hasText(groupId)){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
		if(forumuserinforumgroup!=null){
			throw new AppException("您已经在这个小组了哦");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
		if(forumgroup==null){
			throw new AppException("未找到该小组");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已被解散");
		}
		//小组如果是公开的，加群时无需群主同意
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_public){
			forumgroup.setMemberCount(forumgroup.getMemberCount()+1);
			forumgroupMapper.updateByPrimaryKey(forumgroup);
			Forumuserinforumgroup forumuserinforumgroupNew=new Forumuserinforumgroup();
			forumuserinforumgroupNew.setUserId(userId);
			forumuserinforumgroupNew.setForumGroupId(groupId);
			forumuserinforumgroupNew.setCreateDate(new Date());
			forumuserinforumgroupNew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
			forumuserinforumgroupNew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
			forumuserinforumgroupNew.setUserInForumGroupId(StringUUIdUtil.getUUID());
			forumuserinforumgroupMapper.insert(forumuserinforumgroupNew);
			return true;
		}
		//小组如果是封闭的或者是隐私的，加群时需要群主同意
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_close||forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_private){
			Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = new Forumuserapplyjoingrouprecord();
			forumuserapplyjoingrouprecord.setForumGroupId(groupId);
			forumuserapplyjoingrouprecord.setUserApplyJoinGroupRecordId(StringUUIdUtil.getUUID());
			forumuserapplyjoingrouprecord.setApplyStatus(ForumgroupStatic.apply_status_ing);
			forumuserapplyjoingrouprecord.setUserId(userId);
			forumuserapplyjoingrouprecord.setCreateDate(new Date());
			forumuserapplyjoingrouprecordMapper.insert(forumuserapplyjoingrouprecord);
			return false;
		}
		return true;
	}
	
	/**
	 * 退出小组
	 * @param userId
	 * @param groupId
	 * @return boolean
	 * @author lixs
	 * @date 2017.7.25
	 */
	@Transactional
	public boolean quitGroup(String userId, String groupId){

		logger.info("退出小组");
		if(!StringUtils.hasText(groupId)){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
		if(forumgroup==null){
			throw new AppException("不存在该小组");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已解散");
		}
		//小组创建者退群的话，逻辑删除小组
		if(userId.equals(forumgroup.getLeaderUserId())){
//			forumgroupMapper.deleteByUserIdAndGroupId(forumgroup.getLeaderUserId(), groupId);
			//逻辑删除小组
			forumgroup.setGroupType(ForumgroupStatic.forum_group_type_for_delete);
			forumgroup.setMemberCount(0);
			forumgroupMapper.updateByPrimaryKeySelective(forumgroup);
			//删除小组与用户的关联记录
			forumuserinforumgroupMapper.deleteByForumgroupId(groupId);
			
			//调用环信接口：解散群组
			friendsClient.deleteGroup(forumgroup.getHuanxinGroupId());
			logger.info("解散小组");
			return true;
			}

		//普通成员退群，则删去他与小组关联的记录
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
		if(forumuserinforumgroup==null){
			throw new AppException("您已不在该小组中");
		}
		
		//如果是邀请进群，则用户退群时删除用户的邀请记录
		Forumgroupinvitationrecord forumgroupinvitationrecord =forumgroupinvitationrecordMapper.selectByGroupIdAndUserId(userId, groupId);
		if(null!=forumgroupinvitationrecord){
			//删除用户的邀请记录
			forumgroupinvitationrecordMapper.deleteByPrimaryKey(forumgroupinvitationrecord.getGroupInvitationRecordId());
		}
		
		//如果是通过申请进群，则用户退群时删除用户的申请状态，置为申请被拒绝
		Forumuserapplyjoingrouprecord applyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, groupId);
		if(null!=applyjoingrouprecord){
			applyjoingrouprecord.setApplyStatus(ForumgroupStatic.not_in_group);
			forumuserapplyjoingrouprecordMapper.updateByPrimaryKeySelective(applyjoingrouprecord);
			logger.info("申请记录的状态值为"+applyjoingrouprecord.getApplyStatus());
			
			//调用环信接口，移除单个群组成员
			friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
			//删除本地的群组与用户的关联记录
			forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);
			
			List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
			forumgroup.setMemberCount(forumuserinforumgroupnew.size());
			forumgroupMapper.updateByPrimaryKey(forumgroup);
			return true;
		}
		
		//调用环信接口，移除单个群组成员
		friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
		//删除本地的群组与用户的关联记录
		
		forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);
		
		List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
		forumgroup.setMemberCount(forumuserinforumgroupnew.size());
		forumgroupMapper.updateByPrimaryKey(forumgroup);
		return true;
	}
	
	/**
	 * 获取小组的成员id
	 * @param groupId
	 * @return List<String>
	 * @author lid
	 * @date 2017.6.25
	 */
	@Transactional
	public List<String> getMembersInGroup(String groupId){
		/**
		 * lxs
		 */
		logger.info("获取小组成员ID");
		if(!StringUtils.hasText(groupId)){
			throw new AppException("小组id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
		if(forumgroup==null){
			throw new AppException("小组信息为空");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已被解散");
		}
		//调用环信接口，获取小组成员信息
//		friendsClient.getGroupUsers(forumgroup.getHuanxinGroupId());
		List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectByGroupId(groupId);
		List<String> userId = new ArrayList<>();
		for(Forumuserinforumgroup fusergroup:forumuserinforumgroup){
				userId.add(fusergroup.getUserId());
		}
		return userId;
	}
	
	/**
	 * 小组的设置
	 * @param forumgroup
	 * @return boolean
	 * @author lixs
	 * @Date 2017.7.10
	 */
	@Transactional
	public int groupPrivacySetting(String forumGroupId,String groupName,String groupIntroduction,Integer privacySetting,
								   Double longitude,Double latitude,String groupStyle,String address){
		logger.info("小组的设置");
		if(!StringUtils.hasText(forumGroupId)){
			throw new AppException("小组id为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumGroupId);
		if(forumgroup==null){
			throw new AppException("未查到该小组信息");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已被解散");
		}
		if(groupName.length()>15){
			throw new AppException("小组名称长度不能超过15个字符");
		}
		if(groupIntroduction.length()>200){
			throw new AppException("小组简介不能超过200个字符");
		}
		String maxUser = String.valueOf(maxusers);
		//调用环信接口：修改小组设置
		friendsClient.modifyGroupDetails(forumgroup.getHuanxinGroupId(), groupName, groupIntroduction, maxUser);
		
		return forumgroupMapper.updateByPrimaryKeyForprivacy(forumGroupId, groupName, groupIntroduction, privacySetting,
															longitude, latitude,groupStyle,address);
	}
	/**
	 *  群主将人踢出群
	 * @param userId
	 * @param groupId
	 * @param leaderId
	 * @author Lixs
	 * @Date 2017.7.11
	 */
	@Transactional
	public int quitGroupByLeader(String leaderUserId,String userId,String groupId){
		logger.info("小组创建者踢人出群");
		if(!StringUtils.hasText(userId)){
			throw new AppException("群员id为空");
		}
		if(!StringUtils.hasText(leaderUserId)){
			throw new AppException("群主id为空");
		}
		if(!StringUtils.hasText(groupId)){
			throw new AppException("小组id为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
		if(forumgroup==null){
			throw new AppException("未找到该小组的信息");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		if(!leaderUserId.equals(forumgroup.getLeaderUserId())){
			throw new AppException("你不是群主，无法移除小组成员");
		}
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
		if(forumuserinforumgroup==null){
			throw new AppException("小组中不存在该用户");
		}
		if(forumgroup.getLeaderUserId().equals(userId)){
			throw new AppException("无法移除群主 ");
		}
		
		//如果是邀请进群，则用户退群时删除用户的邀请记录
		Forumgroupinvitationrecord forumgroupinvitationrecord =forumgroupinvitationrecordMapper.selectByGroupIdAndUserId(userId, groupId);
		if(null!=forumgroupinvitationrecord){
			//删除用户的邀请记录
			forumgroupinvitationrecordMapper.deleteByPrimaryKey(forumgroupinvitationrecord.getGroupInvitationRecordId());
		}
		
		//如果该用户是通过申请加群，则退群时将申请记录的状态置为申请拒绝加群
		Forumuserapplyjoingrouprecord applyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, groupId);
		if(null!=applyjoingrouprecord){
			applyjoingrouprecord.setApplyStatus(ForumgroupStatic.not_in_group);
			forumuserapplyjoingrouprecordMapper.updateByPrimaryKeySelective(applyjoingrouprecord);
			
			//调用环信接口，移除单个群组成员
			friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
			//删除本地的群组与用户的关联记录
			forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);
			
			List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
			forumgroup.setMemberCount(forumuserinforumgroupnew.size());
			return forumgroupMapper.updateByPrimaryKey(forumgroup);
		}
		
		
		//调用环信，移除单个群组成员
		friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
		forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);
		
		List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
		forumgroup.setMemberCount(forumuserinforumgroupnew.size());
		return forumgroupMapper.updateByPrimaryKey(forumgroup);
	}
	
	/**
	 * 通过组名模糊查询小组信息
	 * @param userId
	 * @param groupName
	 * @param currentPage
	 * @param rows
	 * @return
	 */
	@Transactional
	public List<ForumInUserGroupVo> selectByGroupName(String userId,String groupName,Integer currentPage,Integer rows){
		logger.info("通过组名查询小组信息");
		PageHelper.startPage(currentPage, rows);
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		List<ForumInUserGroupVo> forumInUserGroupVo = forumgroupMapper.selectByGroupName(userId,groupName);
		if(forumInUserGroupVo==null){
			throw new AppException("未查到相关小组信息");
		}
		return forumInUserGroupVo;
	}
	
	/**
	 * 通过小组id来查询小组信息
	 * @param forumgroupId
	 * @author lixs
	 * @Date 2017.7.20
	 */
	@Transactional
	public Forumgroup selectGroupById(String forumgroupId){
		if(forumgroupId==null){
			throw new AppException("小组id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
		if(forumgroup==null){
			throw new AppException("不存在该小组");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		return forumgroup;
	}
	
	
	/**
	 * 多条件查询小组信息(后台页面)
	 * @param groupName
	 * @param privacy
	 * @param createDateS
	 * @param createDateE
	 * @author lixs
	 * @Date 2017.7.25
	 */
	@Transactional
	public List<Forumgroup> selectGroupByNameAndDateByPage(String groupName,Integer privacy,String createDateS,String createDateE,Integer currentPage,Integer rows){
		logger.info("多条件查询小组信息");
		PageHelper.startPage(currentPage, rows);
		List<Forumgroup> forumgroup = forumgroupMapper.selectGroupByNameAndDate(groupName, privacy, createDateS, createDateE);
		if(forumgroup==null){
			throw new AppException("未查到用户信息");
		}
		return forumgroup;
	}
	
	
	/**
	 * 创建小组（系统小组）
	 * @param forumgroup
	 * @author lixs
	 * @Date 2017.7.26
	 */
	@Transactional
	public Boolean saveSystemForumGroupBatch(List<BatchVo> forumgroup){
		logger.info("saveForumGroup!");
		if(null == forumgroup){
			throw new AppException("forumgroup参数为空！");
		} 
		//调用环信接口，创建小组
		for(int index=750;index<forumgroup.size();index++){
		logger.info("执行次数"+index+forumgroup.size());
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("groupname", forumgroup.get(index).getGroupName());
		resultMap.put("desc", "这是一个分享快乐的小组!");
		resultMap.put("public",true);
		//设置群最大人数（包含群主）
		resultMap.put("maxusers", maxusers);
		resultMap.put("members_only", false);
		//allowinvites 是否允许群成员邀请别人加入此群。 true：允许群成员邀请人加入此群
		resultMap.put("allowinvites", true);
		resultMap.put("owner","16050746"
				+ "gorh94ir3273");
		resultMap.put("members", null);
		
		//解析环信返回的json
		String result = friendsClient.createGroupUser(resultMap).getData();
		HuanxinJson huanxinJson = GSON.fromJson(result, HuanxinJson.class);

		//创建小组
		Forumgroup forumgroupNew = new Forumgroup();
		forumgroupNew.setCreateDate(new Date());
		forumgroupNew.setMemberCount(1);
		forumgroupNew.setForumGroupId(StringUUIdUtil.getUUID()); 
		forumgroupNew.setPrivacySetting(ForumgroupStatic.privacy_public);
		forumgroupNew.setGroupName(forumgroup.get(index).getGroupName());
		forumgroupNew.setLeaderUserId("16050746gorh94ir3273");
		//小组创建者的昵称和头像是动态从用户表中获取。
		forumgroupNew.setLeaderUserNickname(userFeignClient.getUser("16050746gorh94ir3273").getData().getName());
		forumgroupNew.setLeaderUserHeadUrl(userFeignClient.getUser("16050746gorh94ir3273").getData().getImageUrl());
		forumgroupNew.setLongitude(forumgroup.get(index).getLongitude());
		forumgroupNew.setLatitude(forumgroup.get(index).getLatitude());
		forumgroupNew.setGroupIntroduction("这是一个快乐的小组");
		forumgroupNew.setHuanxinGroupId(huanxinJson.data.groupid);
		forumgroupNew.setAddress(forumgroup.get(index).getAddress());
		forumgroupNew.setGroupMessageTotal(0);
		//系统群的头像默认与背景图一致
		forumgroupNew.setHeadUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/165j3tb5jsiuhuxs680w.jpg");
		forumgroupNew.setGroupBackgroundUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/165j3tb5jsiuhuxs680w.jpg");
		forumgroupNew.setGroupType(ForumgroupStatic.forum_group_type_for_system);
//		forumgroupNew.setGroupNotice(userFeignClient.getUser("15zouzi90truhdk1fcmh").getData().getName()+"创建了小组"+forumgroup.get(index).getGroupName());
		forumgroupMapper.insertSelective(forumgroupNew);
		
		logger.info("创建本地小组成功次数"+index);
		logger.info("第"+index+"次群组的id"+forumgroupNew.getForumGroupId());
		//创建群主与小组的关联
		Forumuserinforumgroup forumuserinforumgroupLeader = new Forumuserinforumgroup();
		forumuserinforumgroupLeader.setUserInForumGroupId(StringUUIdUtil.getUUID());
		forumuserinforumgroupLeader.setCreateDate(new Date());
		forumuserinforumgroupLeader.setForumGroupId(forumgroupNew.getForumGroupId());
		forumuserinforumgroupLeader.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
		forumuserinforumgroupLeader.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
		forumuserinforumgroupLeader.setUserId("16050746gorh94ir3273");
		forumuserinforumgroupMapper.insert(forumuserinforumgroupLeader);
		}
		return true;
	}
	
	/**
	 * 首页设置是否显示群成员帖
	 * @param forumgroupId
	 * @param userId
	 * @return
	 */
	@Transactional
	public int updateGroupMessageSetting(String forumgroupId,String userId,Integer status){
		if(!StringUtils.hasText(forumgroupId)){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		if(status==null){
			throw new AppException("是否显示群成员帖状态不能为空");
		}
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroupId);
		if(null ==forumuserinforumgroup){
			throw new AppException("未找到该用户与小组的关联记录");
		}
		forumuserinforumgroup.setUserGroupForumMessageSetting(status);
		return forumuserinforumgroupMapper.updateByPrimaryKeySelective(forumuserinforumgroup);
	}
	
	/**
	 * 更改小组的背景图片
	 * @param forumgroupId
	 * @param backGroundImg
	 * @author lixs
	 * @Date 2017.7.29
	 */
	@Transactional
	public int UpdateGroupBackgroundImg(String forumgroupId,String backGroundImg,String leaderUserId){
		if(!StringUtils.hasText(forumgroupId)){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(backGroundImg)){
			throw new AppException("小组背景图片不能为空");
		}
		if(!StringUtils.hasText(leaderUserId)){
			throw new AppException("群主id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
		if(null==forumgroup){
			throw new AppException("小组信息为空");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		if(!leaderUserId.equals(forumgroup.getLeaderUserId())){
			throw new AppException("你不是群主，无法更改群组背景图片");
		}
		forumgroup.setGroupBackgroundUrl(backGroundImg);
		return forumgroupMapper.updateByPrimaryKey(forumgroup);
	}	
	

	/**
	 * 获取用户列表（除去小组以外的用户）
	 * @param forumgroupId
	 * @lixs
	 * @Date 2017.7.31
	 */
	public List<User> findFriends(String forumgroupId){
		if(!StringUtils.hasText(forumgroupId)){
			throw new AppException("小组id不能为空");
		}
	
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
		if(null==forumgroup){
			throw new AppException("不存在该小组");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		ResultMessage<List<User>> data = friendsClient.findFriends();
		List<User> friendsList = data.getData();
		List<User> users = new ArrayList<User>();
		List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectByGroupId(forumgroupId);
		if(null==forumuserinforumgroup){
			throw new AppException("未能查到小组的相关关联记录");
		}
		for(User user:friendsList){
			Forumuserinforumgroup forumuser = forumuserinforumgroupMapper.selectByUserIdAndGroupId(user.getUserId(), forumgroupId);
			if(null==forumuser){
				users.add(user);
			}
		}	
		return users;
	}
	
	/**
	 * 获取小组详细信息，包含与用户关联的信息
	 * @param userId
	 * @param forumgroupId
	 * @author lixs
	 * @Date 2017.7.31
	 */
	public ForumgroupInUserVo findForumgroupDetails(String userId,String forumgroupId){
		if(!StringUtils.hasText(forumgroupId)){
			throw new AppException("群组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
		if(null==forumgroup){
			throw new AppException("该小组不存在");
		}
		
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		//查出的是群组的基本信息
		ForumgroupInUserVo forumgroupInUserVo = forumgroupMapper.findForumgroupDetails(forumgroupId);
		if(null==forumgroupInUserVo){
			throw new AppException("小组关联信息获取失败");
		}
		//如果用户是群成员，那么会另外查出用户对群的设置
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroupId);
		if(null!=forumuserinforumgroup){
			forumgroupInUserVo.setUserGroupChatSetting(forumuserinforumgroup.getUserGroupChatSetting());
			forumgroupInUserVo.setUserGroupForumMessageSetting(forumuserinforumgroup.getUserGroupForumMessageSetting());
			forumgroupInUserVo.setIsJoin(forumuserinforumgroup.getUserId());
		}
		//如果用户申请过加入该群，则会查出该用户的申请状态
		Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumgroupId);
		if(null!=forumuserapplyjoingrouprecord){
			forumgroupInUserVo.setApplyStatus(forumuserapplyjoingrouprecord.getApplyStatus());
		}
		
		if(userId.equals(forumgroup.getLeaderUserId())){
			forumgroupInUserVo.setApplyStatus(ForumgroupStatic.apply_status_agree);
			forumgroupInUserVo.setIsJoin(forumgroup.getLeaderUserId());
		}
		return forumgroupInUserVo;
	}
	
	/**
	 * 多条件查询小组信息
	 * @param groupName
	 * @param leaderUserName
	 * @param groupType
	 * @param groupStyle
	 * @param memberCountMin
	 * @param memberCountMax
	 * @param groupMessageTotalMin
	 * @param groupMessageTotalMax
	 * @param createDateS
	 * @param createDateE
	 * @param currentPage
	 * @param rows
	 * @author lixs
	 * @Date 2017.8.3
	 */
	public List<Forumgroup> selectForumgroup(String groupName,String leaderUserName,String groupType,String groupStyle,
									   Integer memberCountMin,Integer memberCountMax,Integer groupMessageTotalMin,
									   Integer groupMessageTotalMax,String createDateS,String createDateE,Integer currentPage,
									   Integer rows){
		PageHelper.startPage(currentPage, rows);
		List<Forumgroup> forumgroup = forumgroupMapper.selectForumgroup(groupName, leaderUserName, groupType, groupStyle,
				memberCountMin, memberCountMax, groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE);
		
	
		return forumgroup;
	}
	
	//根据用户id统计小组总数
	public int countGroupByUserId(String userId){
	
		return forumgroupMapper.countGroupByUserId(userId,ForumgroupStatic.forum_group_type_for_delete);
	}
	
	//用来获取查询附近小组的分页数据的总数
	@Transactional
	public List<ForumInUserGroupVo> getNearByGroupsTotal(Double userLongitud,  Double uerLatitude,Integer distance,String userId){
		if(userLongitud==null){
			throw new AppException("用户经度不能为空");
		}
		if(uerLatitude==null){
			throw new AppException("用户纬度不能为空");
		}
		if(distance==null){
			throw new AppException("用户设置的距离不能为空");
		}
		
		double ratio = Math.cos(uerLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  userLongitud - longitudeDistance;
        Double maxLongitude =  userLongitud + longitudeDistance;
        Double minLatitude = uerLatitude - latitudeDistance;
        Double maxLatitude = uerLatitude + latitudeDistance;
		return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,userLongitud,uerLatitude,distance,ForumgroupStatic.privacy_public);
	}
	
	
	//多条件查询的分页数据的总数
	public int countForumgroupTotal(String groupName,String leaderUserName,String groupType,String groupStyle,
			   						 Integer memberCountMin,Integer memberCountMax,Integer groupMessageTotalMin,
			                         Integer groupMessageTotalMax,String createDateS,String createDateE){
		
		return forumgroupMapper.countForumgroupTotal(groupName, leaderUserName, groupType, groupStyle, 
				memberCountMin, memberCountMax, groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE);
	}
	
	
	//获取通过小组名查询小组的总数
	public int selectByGroupNameForTotal(String userId,String groupName){
		return forumgroupMapper.selectByGroupNameForTotal(userId, groupName);
	}

	/**
	 * 获取所有的群组个数
	 * @return int
	 * @author lid
	 * @date 2017.8.7
	 */
	public int countAllGroups(){
		return 	forumgroupMapper.countAllGroups();
	}

	/**
	 * 获取今天创建的群组个数
	 */
	public int countTodayNewGroups(){
		Calendar cal = Calendar.getInstance();
		Date deadTime = new Date();
		cal.setTime(deadTime);

		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		deadTime = cal.getTime();
		Integer todayNewGroups = forumgroupMapper.countTodayNewGroups(deadTime);
		logger.info("todayNewGroups:"+todayNewGroups);
		return todayNewGroups;
	}
	//用户统计附近群组中未加入的群的总数
	@Transactional
	public int getNearByGroupsForOtherGroupTotal(Double userLongitud,  Double userLatitude,Integer distance,String userId){
		
		if(userLongitud==null){
			throw new AppException("用户经度不能为空");
		}
		if(userLatitude==null){
			throw new AppException("用户纬度不能为空");
		}
		if(distance==null){
			throw new AppException("用户设置的距离不能为空");
		}
		
		ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();
		if(null==focusRegion.getData()){
		double ratio = Math.cos(userLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  userLongitud - longitudeDistance;
        Double maxLongitude =  userLongitud + longitudeDistance;
        Double minLatitude = userLatitude - latitudeDistance;
        Double maxLatitude = userLatitude + latitudeDistance;
        return forumgroupMapper.getNearByGroupsForOtherGroupForTotal(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,userLongitud,userLatitude,distance,ForumgroupStatic.privacy_public);
		}
		logger.info("关注区域不为空");
		Double latitude = focusRegion.getData().getLatitude();
		Double longitud = focusRegion.getData().getLongitude();
			
		double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  longitud - longitudeDistance;
        Double maxLongitude =  longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;
        return forumgroupMapper.getNearByGroupsForOtherGroupForTotal(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,longitud,latitude,distance,ForumgroupStatic.privacy_public);
		
		
	}
	
	/**
	 * 群聊消息免打扰
	 * @param userId
	 * @param groupId
	 * @param status
	 * @author lixs
	 * @Date 2017.8.8
	 */
	@Transactional
	public int updateGroupChatSetting(String userId,String groupId,Integer status){
		if(!StringUtils.hasText(groupId)){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		if(status==null){
			throw new AppException("群聊消息免打扰状态不能为空");
		}
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
		if(null==forumuserinforumgroup){
			throw new AppException("未查到用户与小组的记录");
		}
		forumuserinforumgroup.setUserGroupChatSetting(status);
		return forumuserinforumgroupMapper.updateByPrimaryKeySelective(forumuserinforumgroup);
	}
	
	/**
	 * 获取群聊消息免打扰的小组id
	 * @param userId
	 * @author lixs
	 * @Date 2017.8.8
	 */
	@Transactional
	public List<String> selectForumgroupIdByChatSetting(String userId){
	if(!StringUtils.hasText(userId)){
		throw new AppException("用户id不能为空");
		}
	List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectForumgroupIdByChatSetting(userId);
	if(null==forumuserinforumgroup){
		throw new AppException("用户与小组的关联记录为空");
	}
	List<String> forumgroupId = new ArrayList<String>();
	for(int index=0;index<forumuserinforumgroup.size();index++){
		forumgroupId.add(forumuserinforumgroup.get(index).getForumGroupId());
	}
	return forumgroupId;
	}
	
	/**
	 * 筛选出用户未加入群的列表
	 * @param userLongitud
	 * @param uerLatitude
	 * @param distance
	 * @param userId
	 * @param currentPage
	 * @param rows
	 * @author lixs
	 * @Date 2017.8.9
	 */
	@Transactional
	public List<ForumInUserGroupVo> getNearByGroupsForOtherGroup(Double userLongitud,Double userLatitude,Integer distance,String userId,Integer currentPage,Integer rows){
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		if(userLongitud==null){
			throw new AppException("用户经度不能为空");
		}
		if(userLatitude==null){
			throw new AppException("用户纬度不能为空");
		}
		if(distance==null){
			throw new AppException("用户设置的距离不能为空");
		}
		
		PageHelper.startPage(currentPage,rows);
		ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();
		if(null==focusRegion.getData()){
			logger.info("关注区域为空");
		
		double ratio = Math.cos(userLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  userLongitud - longitudeDistance;
        Double maxLongitude =  userLongitud + longitudeDistance;
        Double minLatitude = userLatitude - latitudeDistance;
        Double maxLatitude = userLatitude + latitudeDistance;
        return forumgroupMapper.getNearByGroupsForOtherGroup(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,userLongitud,userLatitude,distance,ForumgroupStatic.privacy_public);
		}
		
		logger.info("关注区域不为空");
		Double latitude = focusRegion.getData().getLatitude();
		Double longitud = focusRegion.getData().getLongitude();
			
		double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude =  longitud - longitudeDistance;
        Double maxLongitude =  longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;
        return forumgroupMapper.getNearByGroupsForOtherGroup(minLongitude, maxLongitude,minLatitude,maxLatitude,userId,longitud,latitude,distance,ForumgroupStatic.privacy_public);
	}
	
	@Transactional
	public int saveSystemForumGroup(Forumgroup forumgroup){
		logger.info("saveForumGroup!");
		if(null == forumgroup){
			throw new AppException("forumgroup参数为空！");
		}
		if(!StringUtils.hasText(forumgroup.getGroupName())){
			throw new AppException("小组名称不能为空");
		}
		if(forumgroup.getGroupName().length()>15){
			throw new AppException("小组名称长度不能超过15个字符");
		}
//		if(forumgroup.getLongitude()==null){
//			throw new AppException("创建小组的经度不能为空");
//		}
//		if(forumgroup.getLatitude()==null){
//			throw new AppException("创建小组的纬度不能为空");
//		}
		if(!StringUtils.hasText(forumgroup.getLeaderUserId())){
			throw new AppException("群主的id不能为空");
		}
		
//		if(!StringUtils.hasText(forumgroup.getAddress())){
//			throw new AppException("群组的地址不能为空");
//		}
		if(!StringUtils.hasText(forumgroup.getGroupIntroduction())){
			throw new AppException("群组介绍不能为空");
		}
				
		//调用环信接口，创建小组
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("groupname", forumgroup.getGroupName());
		resultMap.put("desc", "这是一个分享快乐的小组!");
		resultMap.put("public",true);
		//设置群最大人数（包含群主）
		resultMap.put("maxusers", maxusers);
		resultMap.put("members_only", false);
		//allowinvites 是否允许群成员邀请别人加入此群。 true：允许群成员邀请人加入此群
		resultMap.put("allowinvites", true);
		resultMap.put("owner",forumgroup.getLeaderUserId());
		resultMap.put("members", null);
		
		//解析环信返回的json
		String result = friendsClient.createGroupUser(resultMap).getData();
		HuanxinJson huanxinJson = GSON.fromJson(result, HuanxinJson.class);

		//创建小组
		Forumgroup forumgroupNew = new Forumgroup();
		forumgroupNew.setCreateDate(new Date());
		forumgroupNew.setMemberCount(1);
		forumgroupNew.setForumGroupId(StringUUIdUtil.getUUID()); 
		forumgroupNew.setPrivacySetting(ForumgroupStatic.privacy_public);
		forumgroupNew.setGroupName(forumgroup.getGroupName());
		forumgroupNew.setLeaderUserId(forumgroup.getLeaderUserId());
		//小组创建者的昵称和头像是动态从用户表中获取。
		forumgroupNew.setLeaderUserNickname(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getName());
		forumgroupNew.setLeaderUserHeadUrl(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getImageUrl());
		forumgroupNew.setLongitude(forumgroup.getLongitude());
		forumgroupNew.setLatitude(forumgroup.getLatitude());
		forumgroupNew.setGroupIntroduction(forumgroup.getGroupIntroduction());
		forumgroupNew.setHuanxinGroupId(huanxinJson.data.groupid);
		forumgroupNew.setGroupStyle(forumgroup.getGroupStyle());
		forumgroupNew.setAddress(forumgroup.getAddress());
		forumgroupNew.setGroupMessageTotal(0);
		//系统群的头像默认与背景图一致
		forumgroupNew.setHeadUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/15x0ph5iiwd6wa8s2ta3.png");
		forumgroupNew.setGroupBackgroundUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/15x0ph5iiwd6wa8s2ta3.png");
		forumgroupNew.setGroupType(ForumgroupStatic.forum_group_type_for_system);
		forumgroupNew.setGroupNotice(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getName()+"创建了小组"+forumgroup.getGroupName());
		forumgroupMapper.insertSelective(forumgroupNew);
		
		//创建群主与小组的关联
		Forumuserinforumgroup forumuserinforumgroupLeader = new Forumuserinforumgroup();
		forumuserinforumgroupLeader.setUserInForumGroupId(StringUUIdUtil.getUUID());
		forumuserinforumgroupLeader.setCreateDate(new Date());
		forumuserinforumgroupLeader.setForumGroupId(forumgroupNew.getForumGroupId());
		forumuserinforumgroupLeader.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
		forumuserinforumgroupLeader.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
		forumuserinforumgroupLeader.setUserId(forumgroup.getLeaderUserId());
		return forumuserinforumgroupMapper.insert(forumuserinforumgroupLeader);
	}
	
	@Transactional
	public int selectGroupByNameAndDateForTotal(String groupName,Integer privacy,String createDateS,String createDateE){
		return forumgroupMapper.selectGroupByNameAndDateForTotal(groupName, privacy, createDateS, createDateE);
	}
	
	@Transactional
	public List<Forumgroup> selectGroupAndUserDetailBatch(List<String> huanxinGroupId){
		if(null==huanxinGroupId){
			return null;
		}

		List<Forumgroup> forumgroups =new ArrayList<Forumgroup>();
		for(int index=0;index<huanxinGroupId.size();index++){
			Forumgroup forumgroup = forumgroupMapper.selectGroupDetailByHuanxin(huanxinGroupId.get(index));
			if(null!=forumgroup&&!forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
				forumgroups.add(forumgroup);
			}
			
		}
//		ResultMessage<List<User>> users = userFeignClient.getUsers(userIds.toArray(new String[userIds.size()]));
//		
//		Map<String,Object> mapResult = new HashMap<String, Object>();
//		mapResult.put("forumgroup", forumgroups);
//		mapResult.put("user", users);
		
		return forumgroups;
	}
	
	/**
	 * 批量删除公开群
	 * @author lixs
	 * @Date 2017.8.19
	 */
	@Transactional
	public int deleteGroupForSystemBatch(){
		List<Forumgroup> forumgroup = forumgroupMapper.selectGroupIdForSystem();
		for(int index=0;index<forumgroup.size();index++){
			//删除小组与用户的关联信息
			forumuserinforumgroupMapper.deleteByForumgroupId(forumgroup.get(index).getForumGroupId());
			//物理删除群组
			forumgroupMapper.deleteByPrimaryKey(forumgroup.get(index).getForumGroupId());
			//删除环信小组的信息
			friendsClient.deleteGroup(forumgroup.get(index).getHuanxinGroupId());
		}
		return -1;
	}
	
	/**
	 * 通过环信id获取小组详细信息，包含与用户关联的信息
	 * @param userId
	 * @param huanxinId
	 * @author lixs
	 * @Date 2017.8.25
	 */
	public ForumgroupInUserVo findForumgroupDetailsByHuanxinId(String userId,String huanxinId){
		if(!StringUtils.hasText(huanxinId)){
			throw new AppException("群组id不能为空");
		}
		if(!StringUtils.hasText(userId)){
			throw new AppException("用户id不能为空");
		}
		Forumgroup forumgroup = forumgroupMapper.selectGroupDetailByHuanxin(huanxinId);
		if(null==forumgroup){
			throw new AppException("该小组不存在");
		}
		
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		//查出的是群组的基本信息
		ForumgroupInUserVo forumgroupInUserVo = forumgroupMapper.findForumgroupDetails(forumgroup.getForumGroupId());
		if(null==forumgroupInUserVo){
			throw new AppException("小组关联信息获取失败");
		}
		//如果用户是群成员，那么会另外查出用户对群的设置
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroup.getForumGroupId());
		if(null!=forumuserinforumgroup){
			forumgroupInUserVo.setUserGroupChatSetting(forumuserinforumgroup.getUserGroupChatSetting());
			forumgroupInUserVo.setUserGroupForumMessageSetting(forumuserinforumgroup.getUserGroupForumMessageSetting());
			forumgroupInUserVo.setIsJoin(forumuserinforumgroup.getUserId());
		}
		//如果用户申请过加入该群，则会查出该用户的申请状态
		Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumgroup.getForumGroupId());
		if(null!=forumuserapplyjoingrouprecord){
			forumgroupInUserVo.setApplyStatus(forumuserapplyjoingrouprecord.getApplyStatus());
		}
		
		if(userId.equals(forumgroup.getLeaderUserId())){
			forumgroupInUserVo.setApplyStatus(ForumgroupStatic.apply_status_agree);
			forumgroupInUserVo.setIsJoin(forumgroup.getLeaderUserId());
		}
		return forumgroupInUserVo;
	}
	
	/**
	 * 删除单个小组，逻辑删除(慎用)
	 * @param forumgroupId
	 * @author lixs
	 * @Date 2017.10.19
	 */
	@Transactional
	public int deleteForumgroup(String forumgroupId){
		if(!StringUtils.hasText(forumgroupId)){
			throw new AppException("您未选中任何小组");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
		if(null==forumgroup){
			throw new AppException("该小组不存在");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已被解散，无法继续删除");
		}
		//删除小组与用户的关联记录
		forumuserinforumgroupMapper.deleteByForumgroupId(forumgroupId);
		
		//调用环信接口：解散群组
		friendsClient.deleteGroup(forumgroup.getHuanxinGroupId());
		logger.info("解散小组");
		forumgroup.setGroupType(ForumgroupStatic.forum_group_type_for_delete);
		forumgroup.setMemberCount(0);
		return forumgroupMapper.updateByPrimaryKey(forumgroup);
	}
	
/*	*//**
	 * 导出excel
	 * @param reponse
	 *//*
	public void export(HttpServletResponse reponse){
	//创建HSSFWorkbook对象(excel的文档对象)
    HSSFWorkbook wb = new HSSFWorkbook();
	//建立新的sheet对象（excel的表单）
	HSSFSheet sheet=wb.createSheet("群组表");
	//在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
	HSSFRow row1=sheet.createRow(0);
	//创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
	HSSFCell cell=row1.createCell(0);
	//设置单元格内容
	cell.setCellValue("学员考试成绩一览表");
	//合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
	sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
	//在sheet里创建第二行
	HSSFRow row2=sheet.createRow(1);    
	      //创建单元格并设置单元格内容
	      row2.createCell(0).setCellValue("姓名");
	      row2.createCell(1).setCellValue("班级");    
	      row2.createCell(2).setCellValue("笔试成绩");
	      row2.createCell(3).setCellValue("机试成绩");    
	      //在sheet里创建第三行
	      HSSFRow row3=sheet.createRow(2);
	      row3.createCell(0).setCellValue("李明");
	      row3.createCell(1).setCellValue("As178");
	      row3.createCell(2).setCellValue(87);    
	      row3.createCell(3).setCellValue(78);    
	  //.....省略部分代码


	//输出Excel文件
	    OutputStream output;
		try {
			output = reponse.getOutputStream();
			 reponse.reset();
			    reponse.setHeader("Content-disposition", "attachment; filename=details.xls");
			    reponse.setContentType("application/msexcel");        
			    wb.write(output);
			    output.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   
	}*/

}

